package com.gongpingjialoan.utility;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gongpingjialoan.BuildConfig;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.cc.Const;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description 常用工具方法类
 * @since 2014.1.7
 */
public class Utils {

    private static final String LOG_FILE_NAME = "debug.log";
    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";
    public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";

    public static void debug(String message) {
        if (Const.IS_DEBUG) {
            System.out.println(message);
            //output(message);
        }
    }

    public static void debug(String tag, String message) {
        if (Const.IS_DEBUG) {
            Log.v(tag, message);
            //output(message);
        }
    }

    public static float getFloat(final float value, final float minValue, final float maxValue) {
        return Math.min(maxValue, Math.max(minValue, value));
    }

    public static boolean listIsEmpty(List list) {
        if (list != null && !list.isEmpty())
            return false;
        return true;
    }


    public static boolean isLing(String eval_price) {
        if (TextUtils.isEmpty(eval_price)) return true;
        double price;
        try {
            price = Double.parseDouble(eval_price);
        } catch (NumberFormatException e) {
            return true;
        }
        if (price > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Create a color integer value with specified alpha.
     * <p>This may be useful to change alpha value of background color.</p>
     *
     * @param alpha     Alpha value from 0.0f to 1.0f.
     * @param baseColor Base color. alpha value will be ignored.
     * @return A color with alpha made from base color.
     */
    public static int getColorWithAlpha(float alpha, int baseColor) {
        int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
        int rgb = 0x00ffffff & baseColor;
        return a + rgb;
    }

    /**
     * @param res
     * @param resId
     * @param reqWidth
     * @param reqHeight
     * @return
     * @description 从Resources中加载图片
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置成了true,不占用内存，只获取bitmap宽高
        BitmapFactory.decodeResource(res, resId, options); // 第一次解码，目的是：读取图片长宽
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 调用上面定义的方法计算inSampleSize值
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeResource(res, resId, options); // 产生一个稍大的缩略图
        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize); // 通过得到的bitmap进一步产生目标大小的缩略图
    }


    /**
     * @param src
     * @param dstWidth
     * @param dstHeight
     * @return
     * @description 通过传入的bitmap，进行压缩，得到符合标准的bitmap
     */
    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {
        // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) { // 如果没有缩放，那么不回收
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

    /**
     * @param options   参数
     * @param reqWidth  目标的宽度
     * @param reqHeight 目标的高度
     * @return
     * @description 计算图片的压缩比率
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    /**
     * @param pathName
     * @param reqWidth
     * @param reqHeight
     * @return
     * @description 从SD卡上加载图片
     */
    public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize);
    }


    public static void setTextViewImage(Context context, TextView textViewImage, int imageId, int colorId) {
        Drawable drawable = context.getResources().getDrawable(imageId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textViewImage.setCompoundDrawables(null, null, drawable, null);
        textViewImage.setTextColor(context.getResources().getColor(colorId));
    }


    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }


    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }


    public static String getTimeToNotification() {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        return df.format(new Date());
    }

    //获取城市名字
    public static String getCityName(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("user_city", Context.MODE_PRIVATE);
        String user_city = sharedPreferences.getString("city", "");
        if (TextUtils.isEmpty(user_city)) {
            if (!UserLocation.getInstance().isIslocation()) {
                return "北京";
            } else {
                return UserLocation.getInstance().getCity();
            }
        } else {
            return user_city;
        }
    }

    public static void changeCity(String city) {
        NetDataJson changeCityNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                SharedPreferencesUtil.put(GPJApplication.getInstance(), "isChangeCity", true);
                if (MainActivity.main != null) {
                    if (MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
                        MainActivity.main.assessmentFragment.mMainRecomendView.getRecomendCars();
                        MainActivity.main.assessmentFragment.gooddealers.getDealersData();
                    }
                }
            }
        });
        changeCityNetDataJson.setUrl(API.changeCity);
        changeCityNetDataJson.addParam("city", city);
        changeCityNetDataJson.request("post");
    }


    public static String getLocationName() {
        if (!UserLocation.getInstance().isIslocation()) {
            return "北京";
        } else {
            return UserLocation.getInstance().getCity();
        }
    }


    public static SpannableStringBuilder changeColor(Context context, String title, int front, int behind, int color) {
        ForegroundColorSpan mileForegroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(color));
        SpannableStringBuilder mileBuilder = new SpannableStringBuilder(title);
        mileBuilder.setSpan(mileForegroundColorSpan, front, behind, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return mileBuilder;
    }


    public static SpannableStringBuilder changeColor3(Context context, String title, int front1, int behind1, int front2, int behind2, int front3, int behind3, int color) {
        ForegroundColorSpan mileForegroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(color));
        SpannableStringBuilder mileBuilder = new SpannableStringBuilder(title);

        mileBuilder.setSpan(mileForegroundColorSpan, front1, behind1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mileBuilder.setSpan(mileForegroundColorSpan, front2, behind2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mileBuilder.setSpan(mileForegroundColorSpan, front3, behind3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return mileBuilder;
    }

    /**
     * 获取application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                        if (TextUtils.isEmpty(resultData)) {
                            int data = applicationInfo.metaData.getInt(key);
                            resultData = data + "";
                        }
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }

    /**
     * 两个时间之间的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int getDays(String date1, long date2) {
        long time = Long.parseLong(date1) * 1000;
        if (date1 == null || date1.equals(""))
            return 0;
        long day = (new Date(date2).getTime() - new Date(time).getTime()) / (24 * 60 * 60 * 1000);
        return (int) Math.ceil(day);
    }


    public static String getTimeByTimestamp(String stamp, long current) {
        long time = Long.parseLong(stamp) * 1000;
        Calendar timeCalendar = Calendar.getInstance();
        timeCalendar.setTime(new Date(time));
        Calendar currentCalendar = Calendar.getInstance();
        currentCalendar.setTime(new Date(current));

        if (currentCalendar.get(Calendar.DAY_OF_YEAR) == timeCalendar.get(Calendar.DAY_OF_YEAR)) {
            long t = current - time;
            long nh = 1000 * 60 * 60;
            int hour = (int) (t / nh);//计算差多少小时
            if (hour == 0) {
                return "1小时内";
            }
            return hour + "小时前";
        } else {
            timeCalendar.add(Calendar.DAY_OF_YEAR, 1);
            if (currentCalendar.get(Calendar.DAY_OF_YEAR) == timeCalendar.get(Calendar.DAY_OF_YEAR)) {
                return "昨天";
            }
            timeCalendar.add(Calendar.DAY_OF_YEAR, 1);
            if (currentCalendar.get(Calendar.DAY_OF_YEAR) == timeCalendar.get(Calendar.DAY_OF_YEAR)) {
                return "前天";
            }
            timeCalendar.add(Calendar.DAY_OF_YEAR, -2);
            SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
            return sf.format(timeCalendar.getTime());
        }
    }


    //获取剩余的时间
    public static List<String> dateListDiff(long diff) {

        List<String> times = new ArrayList<>(3);
        long a_hour = 0;
        //按照传入的格式生成一个simpledateformate对象
        //SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 24 * 60 * 60;//一天的毫秒数
        long nh = 60 * 60;//一小时的毫秒数
        long nm = 60;//一分钟的毫秒数
        long ns = 1;//一秒钟的毫秒数
        //获得两个时间的毫秒时间差异

        long day = diff / nd;//计算差多少天
        long hour = diff % nd / nh;//计算差多少小时
        long min = diff % nd % nh / nm;//计算差多少分钟
        long sec = diff % nd % nh % nm / ns;//计算差多少秒
        if (day > 0) {
            a_hour = day * 24;
        }
        if (hour > 0) {
            a_hour += hour;
        }
        if (a_hour >= 10) {
            times.add(a_hour + "");
        } else if (a_hour < 10 && a_hour > 0) {
            times.add("0" + a_hour);
        } else {
            times.add("00");
        }
        if (min >= 10) {
            times.add(min + "");
        } else if (min < 10 && min > 0) {
            times.add("0" + min);
        } else {
            times.add("00");
        }
        if (sec >= 10) {
            times.add(sec + "");
        } else if (sec < 10 && sec > 0) {
            times.add("0" + sec);
        } else {
            times.add("00");
        }
        //输出结果
        return times;
    }


    // 获取特卖中剩余的时间
    public static SpannableStringBuilder dateDiff(long diff, Context context) {
        // 按照传入的格式生成一个simpledateformate对象
        // SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 24 * 60 * 60;// 一天的毫秒数
        long nh = 60 * 60;// 一小时的毫秒数
        long nm = 60;// 一分钟的毫秒数
        long ns = 1;// 一秒钟的毫秒数
        // 获得两个时间的毫秒时间差异

        long day = diff / nd;// 计算差多少天
        long hour = diff % nd / nh;// 计算差多少小时
        long min = diff % nd % nh / nm;// 计算差多少分钟
        long sec = diff % nd % nh % nm / ns;// 计算差多少秒
        StringBuilder sb = new StringBuilder();
        sb.append("离结束 还剩");
        // if (day > 0) {
        // sb.append(day + "天");
        // }
        // if (hour > 0) {
        // sb.append(hour + "小时");
        // }
        // if (min > 0) {
        // sb.append(min + "分");
        // }
        if (day <= 0) {
            if (hour <= 0) {
                if (min <= 0) {
                    sb.append(sec + "秒");
                } else {
                    sb.append(min + "分");
                    sb.append(sec + "秒");
                }
            } else {
                sb.append(hour + "小时");
                sb.append(min + "分");
                sb.append(sec + "秒");
            }
        } else {
            sb.append(day + "天");
            sb.append(hour + "小时");
            sb.append(min + "分");
            sb.append(sec + "秒");
        }

        // 输出结果
        return strColor(sb.toString(), day + "", hour + "", min + "", sec + "",
                context);
    }

    private static SpannableStringBuilder strColor(String newcontent,
                                                   String day, String hour, String min, String sec, Context context) {
        int day_start = newcontent.indexOf(day + "天");
        int hour_start = newcontent.indexOf(hour + "小时");
        int min_start = newcontent.indexOf(min + "分");
        int sec_start = newcontent.indexOf(sec + "秒");
        SpannableStringBuilder style = new SpannableStringBuilder(newcontent);

        if (day_start >= 0) {
            style.setSpan(new ForegroundColorSpan(context.getResources()
                            .getColor(R.color.text_orange_dark)), day_start,
                    day_start + day.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (hour_start >= 0) {
            style.setSpan(new ForegroundColorSpan(context.getResources()
                    .getColor(R.color.text_orange_dark)), hour_start, hour_start
                    + hour.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (min_start >= 0) {
            style.setSpan(new ForegroundColorSpan(context.getResources()
                            .getColor(R.color.text_orange_dark)), min_start,
                    min_start + min.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (sec_start >= 0) {
            style.setSpan(new ForegroundColorSpan(context.getResources()
                            .getColor(R.color.text_orange_dark)), sec_start,
                    sec_start + sec.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return style;
    }


    //获取剩余的时间
    public static String dateDiff(long diff) {

        //按照传入的格式生成一个simpledateformate对象
        //SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 24 * 60 * 60;//一天的毫秒数
        long nh = 60 * 60;//一小时的毫秒数
        long nm = 60;//一分钟的毫秒数
        long ns = 1;//一秒钟的毫秒数
        //获得两个时间的毫秒时间差异

        long day = diff / nd;//计算差多少天
        long hour = diff % nd / nh;//计算差多少小时
        long min = diff % nd % nh / nm;//计算差多少分钟
        long sec = diff % nd % nh % nm / ns;//计算差多少秒
        StringBuilder sb = new StringBuilder();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            sb.append(hour + "小时");
        }
        if (min > 0) {
            sb.append(min + "分");
        }
        sb.append(sec + "秒");
        //输出结果
        return sb.toString();
    }


    public static boolean getTodayorNot1(String serverTime) {
        SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
        Date serverDate;
        Date nowDate = new Date();
        try {

            serverDate = sf.parse(serverTime);
            String now = sf.format(nowDate);
            Date creatDate = sf.parse(now);
            if (creatDate.equals(serverDate)) {
                return true;
            }
        } catch (ParseException e) {
        }
        return false;
    }


    public static String getParseDay(String parse, String serverTime) {
        //"yyyy.MM.dd"
        SimpleDateFormat sf = new SimpleDateFormat(parse);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy年MM月dd日");


        try {
            Date date = sf.parse(serverTime);
            return sd.format(date);

        } catch (ParseException e) {
        }
        return serverTime;
    }


    public static String getSellCarTime(String parse) {
        //"yyyy.MM.dd"
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat returnD = new SimpleDateFormat("yyyy-MM-dd HH");
        try {
            Date date = sd.parse(parse);
            int d = date.getHours() + 2;
            return returnD.format(date) + "点-" + d + "点";

        } catch (ParseException e) {
        }
        return parse;
    }

    /**
     * 获取是否为今天，昨天，或者更早
     *
     * @param creatTime
     * @param serverTime
     * @return
     */

    public static String getTodayorNot(String creatTime, String serverTime) {
        String returnString = "今天";
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        Date creatDate, serverDate;
        long nd = 24 * 60 * 60 * 1000;//一天的毫秒数
        try {
            creatDate = sf.parse(creatTime);
            serverDate = sf.parse(serverTime);
            if (creatDate.equals(serverDate)) {
                return "今天";
            }

            if (creatDate.before(serverDate)) {
                Date yesterDay = new Date(serverDate.getTime() - nd);
                if (yesterDay.equals(creatDate)) {
                    return "昨天";
                } else {
                    return "更早";
                }
            }
        } catch (ParseException e) {
        }
        return returnString;
    }


    /**
     * 获取是否为今天，昨天，或者更早
     *
     * @param creatTime
     * @return
     */
    public static String getTodayorNot(String creatTime) {
        String returnString = "今天";
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");

        Date creatDate, serverDate;
        long nd = 24 * 60 * 60 * 1000;//一天的毫秒数
        try {
            creatDate = sf.parse(creatTime);
            serverDate = sf.parse(sf.format(new Date()));
            if (creatDate.equals(serverDate)) {
                return "今天";
            }

            if (creatDate.before(serverDate)) {
                Date yesterDay = new Date(serverDate.getTime() - nd);
                if (yesterDay.equals(creatDate)) {
                    return "昨天";
                } else {
                    return "更早";
                }
            }
        } catch (ParseException e) {
        }
        return returnString;
    }


    /**
     * 获取图片缩略图地址 <br>
     * 最大边长200像素
     *
     * @param url
     * @return
     */
    public static String getThumbUrl(String url) {
        return url + "!200";
    }

    /**
     * 获取图片缩略图地址 <br>
     * 最大边长可变
     *
     * @param url
     * @param max
     * @return
     */
    public static String getThumbUrl(String url, int max) {
        return url + "!" + max;
    }

    private static synchronized void output(String message) {
        File file = new File(Environment.getExternalStorageDirectory(), LOG_FILE_NAME);
        FileOutputStream fos = null;
        DataOutputStream dos = null;
        try {
            fos = new FileOutputStream(file, true);
            dos = new DataOutputStream(fos);
            SimpleDateFormat sdf = new SimpleDateFormat("MM.dd HH:mm:ss", Locale.US);
            String suffix = sdf.format(new Date());
            String content = suffix + "  " + message + "\n";
            dos.writeUTF(content);
        } catch (IOException e) {
            debug(e.toString());
        } catch (Exception e) {
            debug(e.toString());
        } finally {
            try {
                if (dos != null) {
                    dos.flush();
                    dos.close();
                    dos = null;
                }
                if (fos != null) {
                    fos.flush();
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                debug(e.toString());
            }
        }
    }

    /**
     * 判断是否是合法的Email地址
     *
     * @param email
     * @return
     */
    public static boolean isValidEmail(String email) {
        Pattern pattern = Patterns.EMAIL_ADDRESS;
        Matcher mc = pattern.matcher(email);
        return mc.matches();
    }

    /**
     * 判断是否是合法的手机号码
     *
     * @param phone
     * @return
     * @note 如果运营商发布新号段，需要更新该方法
     */
    public static boolean isValidMobilePhoneNumber(String phone) {
        Pattern pattern = Pattern.compile("^(13[0-9]|14[3|5|7|9]|15[0-9]|170|18[0-9])\\d{8}$");
        Matcher mc = pattern.matcher(phone);
        return mc.matches();
    }

    /**
     * 判断是否是合法的固定电话号码
     *
     * @param phone
     * @return
     */
    public static boolean isValidPhoneNumber(String phone) {
        Pattern pattern = Pattern.compile("^(\\(\\d{3,4}-)|(\\d{3,4}-)?\\d{7,8}$");
        Matcher mc = pattern.matcher(phone);
        return mc.matches();
    }

    /**
     * 判断是否是合法的URL
     *
     * @param url
     * @return
     */
    public static boolean isValidURL(String url) {
        Pattern patterna = Patterns.WEB_URL;
        Matcher mca = patterna.matcher(url);
        return mca.matches();
    }

    /**
     * 是否为空
     *
     * @param object
     * @return
     */
    public static boolean isNull(Object object) {
        boolean result;
        if (TextUtils.isEmpty((CharSequence) (object))) {
            result = true;
        } else {
            String str = String.valueOf(object);
            str = str.toLowerCase();
            result = ("null").equals(str);
        }
        return result;
    }

    /**
     * 如果键盘没有收回 自动关闭键盘
     *
     * @param activity Activity
     * @param v        控件View
     */
    public static void autoCloseKeyboard(Activity activity, View v) {
        /** 收起键盘 */
        View view = activity.getWindow().peekDecorView();
        if (view != null && view.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 判断当前应用是否在前台
     *
     * @param context
     * @return
     */
    public static boolean isAppForground(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
        Iterator<RunningAppProcessInfo> i = l.iterator();
        while (i.hasNext()) {
            RunningAppProcessInfo info = i.next();
            if (info.uid == context.getApplicationInfo().uid
                    && info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否为锁屏状态
     *
     * @param c
     * @return
     */
    public final static boolean isScreenLocked(Context c) {
        KeyguardManager mKeyguardManager = (KeyguardManager) c.getSystemService(Context.KEYGUARD_SERVICE);
        return mKeyguardManager.inKeyguardRestrictedInputMode();
    }

    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f"};

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String getMD5(String str) {
        String resultString = null;
        try {
            resultString = new String(str);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    /**
     * 唤醒屏幕，如果当前锁屏了
     */
    @SuppressLint("Wakelock")
    public static void notifyScreen(Context context) {
        if (!isScreenLocked(context)) {
            return;
        }
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardLock kl = km.newKeyguardLock("unLock");
        kl.disableKeyguard(); // 解锁
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);// 获取电源管理器对象
        PowerManager.WakeLock wl =
                pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
        wl.acquire(5000);// 点亮屏幕
        // wl.release();//释放
    }

    /**
     * WebView
     *
     * @param html
     * @return
     */
    public static String formatHtmlData(String html) {
        String templates =
                "<html><head><meta content=\"initial-scale=1.0,user-scalable=yes,minimum-scale=1.0,maximum-scale=1.0,width=device-width\" name=\"viewport\" /> <style type=\"text/css\">"
                        + "body {word-break:break-all;background-color:transparent;font-size:16px;line-height:1.5;color:#3E3E3E;padding:8px 8px 0;padding-bottom:10px;background-color:#fff;font-family:Helvetica,STHeiti STXihei,Microsoft JhengHei,Microsoft YaHei,Tohoma,Arial;} "
                        + "iframe{width:100%;margin:10px auto 10px auto;}img{width:100%; margin:10px 0 10px 0;height:auto;} .brand-title{ height:40px; vertical-align:super;} .brand-title img{width:40px; margin:0px;} "
                        + ".brand-title span{color:#1974D2;font-size:18px; vertical-align:super;} .goods-title{border-top:solid 1px #EEEEEE; padding-top:10px; margin-top:10px;} "
                        + ".goods-title .title{font-size:16px; color:#1F1F1F} .goods-title .time{color:#c8c8c8;font-size:12px;}</style></head><body>"
                        + html + "</body></html>";

        // MWMLog.d("", "templates="+templates);
        return templates;
    }

    /**
     * 日志
     *
     * @param msg
     */
    public static void LogD(String msg) {
        if (BuildConfig.LEO_DEBUG) {
            Log.w("GONGPINGJIA", msg);
        }
    }


    public static void callKefu(Context context) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000253500"));
        context.startActivity(intent);
    }

    public static boolean getAppSatus(Context context, String pageName) {

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(20);

        //判断程序是否在栈顶
        if (list.get(0).topActivity.getPackageName().equals(pageName)) {
            return true;
        } else {
            //判断程序是否在栈里
            for (ActivityManager.RunningTaskInfo info : list) {
                if (info.topActivity.getPackageName().equals(pageName)) {
                    return true;
                }
            }
            return false;//栈里找不到，返回3
        }
    }

    /**
     * 错误日志
     *
     * @param msg
     */
    public static void LogE(String msg) {
        Log.e("GONGPINGJIA", msg);
    }

    /**
     * 运行中设置ViewPager滑行速度
     *
     * @param viewPager
     * @param mDuration
     */
    public static void flySetViewPagerDuration(ViewPager viewPager, int mDuration) {
        try {
            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(viewPager.getContext());
            scroller.setFixedDuration(mDuration);
            mScroller.set(viewPager, scroller);
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }

    /***
     * 获取缓存目录
     *
     * @return
     * @throws IOException
     */
    public static String getCacheDir()
            throws IOException {
        if (getSDPath().equals("")) {
            throw new IOException("无SD卡，不进行磁盘缓存");
        }
        String dir = getSDPath() + "/gongpingjia/" + Const.CACHE_DIR + "/";
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String substr = dir.substring(0, 4);
        if (substr.equals("/mnt")) {
            dir = dir.replace("/mnt", "");
        }
        return dir;
    }

    /**
     * 获取SD卡目录
     *
     * @return
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (sdDir != null) {
            return sdDir.getAbsolutePath();
        } else {
            return "";
        }
    }

    /**
     * 将URL HASH算法成短字符串
     *
     * @param url
     * @return
     */
    public static String hashUrl(String url) {
        return MD5(url);
    }

    /**
     * 32位MD5加密算法
     *
     * @param str
     * @return
     */
    public static String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        return str.matches("\\d+");
    }

    public static int compare_date(String DATE1, String DATE2) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /***
     * 获取车龄
     *
     * @return
     */
    public static List<String> getAgeList() {
        List<String> list = new ArrayList<String>();
        list.add("不限");
        list.add("1年以内");
        list.add("1-3年");
        list.add("3-5年");
        list.add("5-8年");
        list.add("8年以上");
        return list;
    }

    /***
     * 获取里程
     *
     * @return
     */
    public static List<String> getLichengList() {
        List<String> list = new ArrayList<String>();
        list.add("公里数不限");
        list.add("0-3万公里");
        list.add("3-8万公里");
        list.add("8-15万公里");
        list.add("15-22万公里");
        list.add("22-30万公里");
        list.add("30万公里以上");
        return list;
    }

    public static List<String> getLichengValue() {
        List<String> list = new ArrayList<String>();
        list.add("");
        list.add("1.5");
        list.add("5.5");
        list.add("11.5");
        list.add("18.5");
        list.add("26");
        list.add("30");
        return list;
    }

    /***
     * 获取价格
     *
     * @return
     */
    public static List<String> getPriceList() {
        List<String> list = new ArrayList<String>();
        list.add("不限");
        list.add("3万元以内");
        list.add("3-5万元");
        list.add("5-8万元");
        list.add("8-10万元");
        list.add("10-15万元");
        list.add("15-20万元");
        list.add("20-30万元");
        list.add("30-50万元");
        list.add("50万以上");
        return list;
    }

    /***
     * 获取排序
     *
     * @return
     */
    public static List<String> getSortList() {
        List<String> list = new ArrayList<String>();
        list.add("价格升序");
        list.add("价格降序");
        list.add("最新鲜");
        list.add("里程少");
        return list;
    }

    /***
     * 查询车况描述
     *
     * @return
     */
    public static List<List<String>> getCarStatusData() {
        List<List<String>> list = new ArrayList<List<String>>();

        List<String> excellentlist = new ArrayList<String>();
        excellentlist.add("没有出过任何事故");
        excellentlist.add("有完整的4S店保养记录");
        excellentlist.add("全车仅少量剐蹭痕迹需要补漆");
        excellentlist.add("车辆内饰轻微磨损或少量污渍");
        excellentlist.add("发动机，变速箱没有任何问题");
        excellentlist.add("电子设备全部正常");

        List<String> goodlist = new ArrayList<String>();
        goodlist.add("仅发生过少量小碰擦事故，只伤及车辆表面");
        goodlist.add("有完整或部分4S店保养记录");
        goodlist.add("全车需补漆不超过4处，局部钣金不超过3处");
        goodlist.add("车辆内饰磨损或污渍不超过4处，使用故障不超过1处");
        goodlist.add("发动机，变速箱能正常工作，没有维修过");
        goodlist.add("电子设备最多不超过1处故障");

        List<String> fairlist = new ArrayList<String>();
        fairlist.add("发生过一些轻微撞击事故，更换或修复过零部件，但不伤及车辆骨架");
        fairlist.add("有部分4S店保养记录或无保养记录");
        fairlist.add("全车有多处剐蹭痕迹需要喷漆或做钣金修复");
        fairlist.add("车辆内饰有多处明显的磨损和污渍，需要进行整理清洗");
        fairlist.add("发动机，变速箱未大修过，允许做过轻微维修");
        fairlist.add("部分电子设备存在故障");

        List<String> badlist = new ArrayList<String>();
        badlist.add("发生过严重撞击事故伤及车辆骨架，或是泡过水、被烧过");
        badlist.add("有部分4S店保养记录或无保养记录");
        badlist.add("全车有大量剐蹭痕迹需要喷漆或做钣金修复");
        badlist.add("车辆内饰磨损严重或有大量污渍，需要进行翻新整理");
        badlist.add("发动机，变速箱大修过或需要更换");
        badlist.add("大量电子设备存在故障");

        list.add(excellentlist);
        list.add(goodlist);
        list.add(fairlist);
        list.add(badlist);

        return list;
    }

    public static List<String> getCarStatusCountData() {
        List<String> list = new ArrayList<String>();
        list.add("15%的车属于优秀车况");
        list.add("50%的车属于较好车况");
        list.add("25%的车属于一般车况");
        list.add("10%的车属于较差车况");
        return list;
    }


    public static String getVipCarAge(int age) {
        String result = "";
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(new Date());


        result = (currentCal.get(Calendar.YEAR) - age) + "-" + currentCal.get(Calendar.YEAR);
        return result;
    }

    /**
     * 计算车龄
     *
     * @param years
     */
    public static String getCarYear(String years) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String y = "";

        if (years.equals("不限车龄")) {
            y = "";
        } else if (years.equals("5年以上")) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.YEAR, -5);
            y = "2000-" + (sdf.format(cal.getTime()));
        } else if (years.equals("1年以内")) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.YEAR, -1);
            y = (sdf.format(cal.getTime())) + "-" + (sdf.format(new Date()));
        } else {
            int index = years.lastIndexOf("年");
            String str = years.substring(0, index);
            String[] stra = str.split("-");
            Calendar minCal = Calendar.getInstance();
            minCal.setTime(new Date());
            minCal.add(Calendar.YEAR, -Integer.parseInt(stra[0]));

            Calendar maxCal = Calendar.getInstance();
            maxCal.setTime(new Date());
            maxCal.add(Calendar.YEAR, -Integer.parseInt(stra[1]));

            y = (sdf.format(minCal.getTime())) + "-" + (sdf.format(maxCal.getTime()));
        }

        return y;
    }

    public static boolean isStringNull(String str) {
        if (str == null || str.equals(""))
            return true;
        return false;
    }

    public static int getTextWidth(Paint paint, String str) {
        int iRet = 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] widths = new float[len];
            paint.getTextWidths(str, widths);
            for (int j = 0; j < len; j++) {
                iRet += (int) Math.ceil(widths[j]);
            }
        }
        return iRet;
    }

//    @SuppressLint("NewApi")
//    public static void enableStrictMode() {
//        if (Utils.hasGingerbread()) {
//            StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
//                    new StrictMode.ThreadPolicy.Builder()
//                            .detectAll()
//                            .penaltyLog();
//            StrictMode.VmPolicy.Builder vmPolicyBuilder =
//                    new StrictMode.VmPolicy.Builder()
//                            .detectAll()
//                            .penaltyLog();
//
//            if (Utils.hasHoneycomb()) {
//                threadPolicyBuilder.penaltyFlashScreen();
//                vmPolicyBuilder
//                        .setClassInstanceLimit(ImageGridActivity.class, 1);
//            }
//            StrictMode.setThreadPolicy(threadPolicyBuilder.build());
//            StrictMode.setVmPolicy(vmPolicyBuilder.build());
//        }
//
//
//    }

    public static boolean hasFroyo() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;

    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= 19;
    }

    public static List<Camera.Size> getResolutionList(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        return parameters.getSupportedPreviewSizes();
    }

    public static class ResolutionComparator implements Comparator<Camera.Size> {

        @Override
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if (lhs.height != rhs.height)
                return lhs.height - rhs.height;
            else
                return lhs.width - rhs.width;
        }

    }

    public static void showAsDropDown(View parent, PopupWindow popupWindow) {
        if (Build.VERSION.SDK_INT < 24) {
            popupWindow.showAsDropDown(parent);
        } else {
            // 获取控件的位置，安卓系统>7.0
            int[] location = new int[2];
            parent.getLocationOnScreen(location);
            popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, 0, location[1] + parent.getHeight());
        }
    }

}
